<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>707弹幕助手</title>
        <link rel="stylesheet" href="css/index.css">
        <!-- Stylesheets -->
        <link rel="stylesheet" href="css/photon.min.css">
        <!-- Jquery -->
        <script>window.$ = require('./js/jquery.js')</script>

    </head>
    <body>
        <script>
        /*
         * 弹幕程序
         */
        const net = require('net');

        function start(roomid) {
          // 建立socket连接
          const s = net.connect({ port:8601, host:'openbarrage.douyutv.com' }, () => {
            console.log('connect success');
          });

          const msg = 'type@=loginreq/roomid@=' + roomid + '/';
          sendData(s, msg);

          // 接收数据
          s.on('data', (chunk) => {
            formatData(chunk);
            const msg = 'type@=joingroup/rid@=' + roomid + '/gid@=-9999/';
            sendData(s, msg);
          });

          // 报错信息
          s.on('error', (err) => {
            console.log(err);
          });

          // 设置心跳
          setInterval(() => {
            let timestamp = parseInt(new Date()/1000);
            let msg = 'type@=keeplive/tick@=' + timestamp + '/';
            sendData(s, msg);
          }, 45000);

        }

        // 给弹幕服务器发送消息
        function sendData(s, msg) {
          let data = new Buffer(msg.length + 13);
          data.writeInt32LE(msg.length + 9, 0);
          data.writeInt32LE(msg.length + 9, 4);
          data.writeInt32LE(689, 8);
          data.write(msg + '\0', 12);
          s.write(data);
        }

        // 格式化数据
        function formatData(msg) {
          const sliced = msg.slice(12).toString();
          // 减二删掉最后的'/'和'\0'
          const splited = sliced.substring(0, sliced.length - 2).split('/');
          const map = formatDanmu(splited);
          analyseDanmu(map);
        }

        // 格式化收到的弹幕，存入map
        function formatDanmu(msg) {
          let map = {};
          for (let i in msg) {
            let splited = msg[i].split('@=');
            map[splited[0]] = splited[1];
          }
          return map;
        }

        // 识别弹幕信息
        function analyseDanmu(msg) {
          if (msg['type'] == 'chatmsg') {
            updateMsg(msg['nn'], msg['txt']);
          }
        }
        function analyseDanmu(msg) {
          if (msg['type'] == 'chatmsg') {
            updateMsg(msg['nn'], msg['txt']);
          }
          if (msg['type'] == 'uenter') {
            updateMsg('[' + msg['nn'] + ']', '进入房间');
          }
          if (msg['type'] == 'dgb') {
            updateMsg('[' + msg['nn'] + ']', '送礼物啦');
          }
        }

        // 更新页面数据
        function updateMsg(nn, txt) {
          var content = document.getElementById('messages');
          content.innerHTML += '<tr><td><span class="uname">' + nn + '</span>:' + txt + '</td></tr>';
          // 滚动条始终在最下面
          var pane = document.getElementById('pane');
          pane.scrollTop = pane.scrollHeight;

          // notification
          let notifier = new Notification(nn, {
            body: txt
          });
        }

        // 设置房间号
        function setRoomId() {
          var roomid = document.getElementById('roomid').value;
          var content = document.getElementById('pane');
          content.innerHTML = "<table class='table-striped'><tbody id='messages'></tbody></table>";
          start(roomid);

          const {ipcRenderer} = require('electron');
          ipcRenderer.send('asynchronous-message', 'ping');
        }

        $(document).ready(function () {
          const {shell} = require('electron');
          const githubLink = document.getElementById('github');
          githubLink.addEventListener('click', function (event) {
            shell.openExternal('http://github.com/zephyrzoom');
          });
        });


        </script>
        <div class="window">
          <div class="window-content">
            <div class="pane-group">
              <div class="pane" id="pane">
                <from>
                  <div class="form-group">
                    <h5>请输入房间号</h5>
                    <input type="text" class="form-control" placeholder="房间号" id="roomid" maxlength="10">
                    <button onclick="setRoomId()" class="btn btn-primary btn-large">连接</button>
                  </div>
                </form>
              </div>
            </div>
          </div>
          <footer class="toolbar toolbar-footer">
            <h1 class="title"><a id="github"><span class="icon icon-github"></span></a></h1>
          </footer>
        </div>
    </body>
</html>
